package com.example.demo.controller;


import com.alibaba.fastjson.JSON;
import com.example.demo.common.pageResult;
import com.example.demo.common.R;

import com.example.demo.entiy.Employee;
import com.example.demo.service.Employeeservice;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private Employeeservice employeeservice;
    //1、获取数据并将密码通过md5加密
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request,@RequestBody Employee employee){
        try {
            String username = employee.getUsername();
            String possword = employee.getPassword();
            Employee emp = employeeservice.login(username, possword);
            request.getSession().setAttribute("employee",emp.getId());
            return R.success(emp);
        }catch (IllegalArgumentException e){
            return R.error(e.getMessage());
        }
    }
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        return R.success(employeeservice.logout(request));
    }
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee){
        employeeservice.save(request,employee);
        return R.success("添加成功");
    }
    @GetMapping("/page")
    public R<Object> getInfo(int page, int pageSize, String name){
        pageResult<Employee> page1 = employeeservice.pageInfo(page,pageSize,name);
        return R.success(JSON.toJSON(page1));
    }
    @PutMapping
    public R<String> CharageStatus(HttpServletRequest request,@RequestBody Employee employee){
        //1、获取数据中的id
        //2、修改数据
        Long empId =(Long) request.getSession().getAttribute("employee");
        int i = employeeservice.charageStatus(employee,empId);
        if (i != 1){
            return R.error("修改失败！");
        }
        return R.success("修改成功！");
    }
    @GetMapping("/{id}")
    public R<Employee> getUser(@PathVariable Long id){
        Employee emp =employeeservice.getUser(id);
        return R.success(emp);
    }

}
